package com.example.retailmanagement.service;

import com.example.retailmanagement.mapper.ProductMapper;
import com.example.retailmanagement.model.Product;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {

    private static final Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);

    @Autowired
    private ProductMapper productMapper;

    // 获取所有产品
    @Override
    public List<Product> getAllProducts() {
        logger.info("在ProductService中开始执行获取所有产品的操作");
        List<Product> products = productMapper.getAllProducts();
        logger.info("在ProductService中成功获取到 {} 个产品", products.size());
        return products;
    }

    // 获取指定产品
    @Override
    public Product getProductById(Long id) {
        logger.info("在ProductService中开始执行获取指定产品的操作，产品ID：{}", id);
        Product product = productMapper.getProductById(id);
        logger.info("在ProductService中获取指定产品的结果：{}", product!= null? "找到产品" : "未找到产品");
        return product;
    }

    // 插入新产品
    @Override
    public boolean insertProduct(Product product) {
        logger.info("在ProductService中开始执行插入新产品的操作，新产品信息：{}", product);
        int rowsInserted = productMapper.insertProduct(product);
        boolean result = rowsInserted > 0;
        if (result) {
            logger.info("在ProductService中成功插入新产品，插入行数：{}", rowsInserted);
        } else {
            logger.error("在ProductService中插入新产品失败，插入行数：{}，产品信息：{}", rowsInserted, product);
        }
        return result;
    }

    // 更新指定产品
    @Override
    public boolean updateProduct(Product product) {
        logger.info("在ProductService中开始执行更新指定产品的操作，产品信息：{}", product);
        int rowsUpdated = productMapper.updateProduct(product);
        boolean result = rowsUpdated > 0;
        if (result) {
            logger.info("在ProductService中成功更新指定产品，更新行数：{}", rowsUpdated);
        } else {
            logger.error("在ProductService中更新指定产品失败，更新行数：{}，产品信息：{}", rowsUpdated, product);
        }
        return result;
    }

    // 删除产品
    @Override
    public boolean deleteProduct(Long id) {
        logger.info("在ProductService中开始执行删除产品的操作，产品ID：{}", id);
        int rowsDeleted = productMapper.deleteProduct(id);
        boolean result = rowsDeleted > 0;
        if (result) {
            logger.info("在ProductService中成功删除产品，删除行数：{}", rowsDeleted);
        } else {
            logger.error("在ProductService中删除产品失败，删除行数：{}，产品ID：{}", rowsDeleted, id);
        }
        return result;
    }
}